﻿package me.zhengjie.common.utils

import com.alibaba.fastjson.util.IOUtils
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

/**
 * 说明： MD5工具类
 * 创建人：Kuki
 * 修改时间：2024年11月10日
 * @version
 */
object MD5Util {
    @JvmStatic fun md5(str: String): String {
        var str = str
        try {
            val md = MessageDigest.getInstance("MD5")
            md.update(str.toByteArray())
            val b = md.digest()
            var i: Int
            val buf = StringBuffer("")
            for (offset in b.indices) {
                i = b[offset].toInt()
                if (i < 0) i += 256
                if (i < 16) buf.append("0")
                buf.append(Integer.toHexString(i))
            }
            str = buf.toString()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return str
    }
    private val HEX_DIGITS = arrayOf(
        "0", "1", "2", "3", "4", "5",
        "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"
    )
    @JvmStatic
    fun md5Encode(origin: String?, charsetname: String?): String? {
        var resultString: String? = null
        try {
            resultString = origin
            val md = MessageDigest.getInstance("MD5")
            resultString = if (charsetname == null || "" == charsetname) byteArrayToHexString(
                md.digest(
                    resultString!!.toByteArray(StandardCharsets.UTF_8)
                )
            ) else byteArrayToHexString(
                md.digest(
                    resultString!!
                        .toByteArray(charset(charsetname))
                )
            )
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return resultString
    }

    private fun byteArrayToHexString(b: ByteArray): String? {
        val resultSb = StringBuffer()
        for (i in b.indices) resultSb.append(byteToHexString(b[i]))
        return resultSb.toString()
    }

    private fun byteToHexString(b: Byte): String? {
        var n = b.toInt()
        if (n < 0) n += 256
        val d1 = n / 16
        val d2 = n % 16
        return HEX_DIGITS[d1] + HEX_DIGITS[d2]
    }

   /* @JvmStatic
    fun main(args: Array<String>) {
        println(md5("31119@qq.com" + "123456"))
        println(md5("mj1"))
        println(md5("1234" + "1234567890" + "6e202f23d3db617a3be5aff61d6097b5"))
        println(md5("mp:bcp:123"))
    }*/

    @JvmStatic
    fun encrypt(file: File?): String? {
        var `in`: InputStream? = null
        return try {
            val digest = MessageDigest.getInstance("MD5")
            `in` = FileInputStream(file)
            val buffer = ByteArray(1024) //10k
            var readLen: Int
            while (`in`.read(buffer).also { readLen = it } != -1) {
                digest.update(buffer, 0, readLen)
            }
            toHex(digest.digest())
        } catch (e: java.lang.Exception) {
            ""
        } finally {
            IOUtils.close(`in`)
        }
    }

    @JvmStatic
    fun encrypt(text: String): String? {
        return try {
            val digest = MessageDigest.getInstance("MD5")
            digest.update(text.toByteArray(StandardCharsets.UTF_8))
            toHex(digest.digest())
        } catch (e: java.lang.Exception) {
            ""
        }
    }
    @JvmStatic
    fun encrypt(bytes: ByteArray?): String? {
        return try {
            val digest = MessageDigest.getInstance("MD5")
            digest.update(bytes)
            toHex(digest.digest())
        } catch (e: java.lang.Exception) {
            ""
        }
    }
    @JvmStatic
    private fun toHex(bytes: ByteArray): String? {
        val buffer = StringBuilder(bytes.size * 2)
        for (i in bytes.indices) {
            buffer.append(Character.forDigit(bytes[i].toInt() and 240 shr 4, 16))
            buffer.append(Character.forDigit(bytes[i].toInt() and 15, 16))
        }
        return buffer.toString()
    }
    @JvmStatic
    fun hmacSha1(data: String, encryptKey: String): String? {
        val HMAC_SHA1 = "HmacSHA1"
        val signingKey = SecretKeySpec(encryptKey.toByteArray(StandardCharsets.UTF_8), HMAC_SHA1)
        return try {
            val mac = Mac.getInstance(HMAC_SHA1)
            mac.init(signingKey)
            mac.update(data.toByteArray(StandardCharsets.UTF_8))
            toHex(mac.doFinal())
        } catch (e: java.lang.Exception) {
            ""
        }
    }

    @JvmStatic
    fun sha1(data: String): String? {
        return try {
            val digest = MessageDigest.getInstance("SHA-1")
            toHex(digest.digest(data.toByteArray(StandardCharsets.UTF_8)))
        } catch (e: java.lang.Exception) {
            ""
        }
    }
}
